package com.beone.admin.service;

import com.beone.admin.entity.BasePermission;
import com.beone.admin.entity.BaseUser;
import com.beone.admin.security.SysUser;
import com.beone.admin.security.filter.PermissionsGrantedAuthority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @title  Spring Security 根据用户名鉴权
 * @Author 覃球球
 * @Version 1.0 on 2017/12/20.
 * @Copyright 长笛龙吟
 */
@Service("userDetailsService")
public class UrlSecurityUserDetailsService implements UserDetailsService {

    @Resource(name = "userCache")
    private UserCache userCache;

    @Autowired
    private BaseUserService baseUserService;



    /**
     * 根据用户名 加载用户及用户权限信息
     * @param name
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        SysUser user = (SysUser) this.userCache.getUserFromCache(name);
        if(user == null) {
            user = new SysUser();
            BaseUser adminUser = baseUserService.loadUserByUsername(name);
            if (adminUser == null) {
                throw new UsernameNotFoundException("用户不存在！", null);
            }

            user.setUser(adminUser);
            //得到用户的权限
            authorities = this.loadUserAuthorities(adminUser.getUserId());
            //增加当前用户的URL权限
            user.setAuthorities(authorities);
            BaseUser operationUser=new BaseUser();
            operationUser.setUserId(adminUser.getUserId());
            operationUser.setLastVisit((int)(System.currentTimeMillis()/1000));
            baseUserService.updateById(operationUser);
            this.userCache.putUserInCache(user);
        }
        return user;
    }

    /**
     * 获取当前用户的授权URL
     * @param userId
     */
    public Collection<GrantedAuthority> loadUserAuthorities(Integer userId){
        //获取该用户的 所有权限
        List<BasePermission> permissions = baseUserService.queryPermissions("all",userId);
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (BasePermission permission : permissions) {
            GrantedAuthority grantedAuthority = new PermissionsGrantedAuthority(permission);
            authorities.add(grantedAuthority);
        }
        return authorities;
    }
}
